import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { BusinessCircleService } from '../business-circle.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { defalutImg } from '../comm';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-circle-plate',
  templateUrl: './circle-plate.component.html',
  styleUrls: ['./circle-plate.component.scss']
})
export class CirclePlateComponent implements OnInit {

  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  // 表格data
  tableData: any = [];
  fallback: string = defalutImg;
  
  /******************** model START *********************/
  isModelVisible: boolean = false;
  subLoading: boolean = false;
  modelType: number = 0; // 0：新增，1：编辑
  updateItem: any = {};
  validateForm!: FormGroup;
  bigLoading: boolean = false;
  smallLoading: boolean = false;
  /******************** model END *********************/

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private services: BusinessCircleService,
    public permission: PermissionService,
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      boardName: ['', [Validators.required]], // 板块名称
      boardType: ['', [Validators.required]], // 板块类型
      subtitle: [''], // 副标题
      largeIcon: ['', [Validators.required]], // 大图标
      smallIcon: ['', [Validators.required]], // 小图标
      sort: ['', [Validators.required]], // 排序
      status: ['', [Validators.required]] // 状态
    });

    this.loadTable();
  }

  async loadTable() {
    try {
      this.tableForms.tableLoading = true;
      const res: any = await this.services.getCircleTableData();
      this.tableForms.tableLoading = false;
      if (res.code == 0) {
        this.tableData = res.data || [];
      }
    } catch (error) {
      // console.log(error);
      this.tableData = [];
      this.tableForms.tableLoading = false;
    }
  }

  openModel(num: number, item?: any) {
    this.validateForm.reset();
    this.modelType = num;
    this.updateItem = item;

    if (num == 1) {
      for (let key in this.validateForm.value) {
        this.validateForm.get(key)?.setValue(String(item[key]));
      }
    }
    this.isModelVisible = true;
  }
  
  handleOk() {
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return
    }
    
    if (this.modelType == 0) {
      this.addHandleData();
    } else {
      this.updateHandleData();
    }
  }

  handleCancel(): void {
    this.isModelVisible = false;
  }

  // add handle
  async addHandleData() {
    try {
      this.subLoading = true;
      const res: any = await this.services.addCircleItemData({...this.validateForm.value});
      this.subLoading = false;
      if (res.code == 0) {
        this.message.success('添加成功');
        this.isModelVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message || '添加失败');
      }
    } catch (error: any) {
      this.subLoading = false;
      this.message.error(error);
    }
  }
  // update handle
  async updateHandleData() {
    try {
      this.subLoading = true;
      const res: any = await this.services.updateCircleItemData({...this.validateForm.value, id: this.updateItem.id});
      this.subLoading = false;
      if (res.code == 0) {
        this.message.success('编辑成功');
        this.isModelVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message || '编辑失败');
      }
    } catch (error: any) {
      this.subLoading = false;
      this.message.error(error);
    }
  }

  /**
   * 删除
   * @param item 
   */
  async deleteItem(item: any) {
    try {
      const res: any = await this.services.updateCircleItemData({ id: item.id, deleteState: 1 });
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error) {
      // console.log(error);
    }
  }

  /**
   * 图片上传
   * @param ev 
   * @param num 0：大图标，1：小图标
   */
  onModalPreview(ev: any, num: number) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj, num);
  }
  // uploadInterface
  async uploadInterface(file: any, num: number) {
    if (!file || (num == 0 && this.bigLoading) || (num == 1 && this.smallLoading)) {
      return
    }

    try {
      num == 0 ? this.bigLoading = true : this.smallLoading = true;
      const res: any = await this.services.uploadFileData(file);
      this.bigLoading = false;
      this.smallLoading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        if (num == 0) {
          this.validateForm.get('largeIcon')?.setValue(res.data);
        } else {
          this.validateForm.get('smallIcon')?.setValue(res.data);
        }
      } else {
        this.message.error(res.message || '图片上传失败');
      }
    } catch (error: any) {
      this.bigLoading = false;
      this.smallLoading = false;
      if (num == 0) {
        this.validateForm.get('largeIcon')?.setValue('');
      } else {
        this.validateForm.get('smallIcon')?.setValue('');
      }
      this.message.error(error || '图片上传失败');
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }
}
